//
//  HomeViewController.m
//  TenThousand
//
//  Created by baixue on 16/6/6.
//  Copyright © 2016年 baixue. All rights reserved.
//

#import "HomeViewController.h"
#import "LoginTableViewCell.h"
#import "PurchaseTableViewCell.h"
#import "HeaderTableViewCell.h"
#import "FooterTableViewCell.h"
#import "RegularCell.h"
#import "CurrentViewController.h"
#import "WelcomeLoginViewController.h"
#import "LoginViewController.h"//登录注册页面
#import "RecommendViewController.h"//推荐有礼
#import "InvestmentViewController.h"
#import "ZLScrolling.h"
#import "WalletViewController.h"//萬钱宝
#import "BorrowGetHome.h"//
#import "WantBorrowViewController.h"



@interface HomeViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,ZLScrollingDelegate>
{
    ZLScrolling *_zl;
    
}
@property (nonatomic, strong) UIButton *backView;
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) NSMutableArray *homeArr;
@property (nonatomic, strong) NSMutableArray *moneyArr;



@end
#define StringArray @[@"",@"",@"",@""]
#define TitleArray @[@"每日签到",@"推荐有礼",@"我要投资",@"我要借款"]
#define TitleLable @[@"严格甄选优质生产",@"六层风控安全保障",@"贴心服务便携流程"]
#define lsh
@implementation HomeViewController

- (NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

- (NSMutableArray *)homeArr{
    if (!_homeArr) {
        _homeArr = [NSMutableArray array];
    }
    return _homeArr;
}

- (NSMutableArray *)moneyArr {
    if (!_moneyArr) {
        _moneyArr = [NSMutableArray array];
    }
    return _moneyArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.mytableView];
//    [self getDueOnDemandData];
    
   
    [self refresh];

    [self getSearchImage];
    
    [self getHomeAmount];//获取累计金额
}


#pragma mark -------------tableview开始-------------
- (UITableView *)mytableView{
    if (!_mytableView) {
        _mytableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height) style:UITableViewStyleGrouped];
        _mytableView.dataSource = self;
        _mytableView.delegate = self;
        _mytableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _mytableView.showsVerticalScrollIndicator = NO;
        
    }
    return _mytableView;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
//代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.homeArr.count+3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        HeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
        if (cell == nil) {
            cell = [[HeaderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backView.layer.shadowColor = [UIColor lightGrayColor].CGColor;
        cell.backView.layer.shadowOffset = CGSizeMake(0.5, 0.5);
        cell.backView.layer.shadowOpacity = YES;
        cell.Clicked = ^(NSInteger tag){
            switch (tag)  {
                    
                    //我要投资
                case 1002:
                {
                    // self.tabBarController.selectedIndex = 1;
                    WantBorrowViewController *wantBorrowVC = [[WantBorrowViewController alloc] init];
                    wantBorrowVC.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:wantBorrowVC animated:NO];
                    
                }
                    break;
                    //推荐有礼
                case 1001:
                {
                    self.tabBarController.selectedIndex = 1;
                }
                    break;
                    
                    //我要签到
                case 1000:
                {
                    [self signIn];
                    
                }
                    break;
                case 1003:
                {
                    
                    RecommendViewController *recommendView = [[RecommendViewController alloc] init];
                    recommendView.hidesBottomBarWhenPushed = YES;
                    
                    [self.navigationController pushViewController:recommendView animated:NO];
                    
                    
                }
                    break;
                    
                default:
                    break;
            }
        };
        return cell;
    }else if (indexPath.row == 1) {
        LoginTableViewCell *loginCell = [tableView dequeueReusableCellWithIdentifier:@"LOGINCELL"];
        if (!loginCell) {
            loginCell = [[[NSBundle mainBundle] loadNibNamed:@"LoginTableViewCell" owner:nil options:nil] lastObject];
        }
        
        if (self.moneyArr.count) {
            BorrowGetHome *model = [self.moneyArr firstObject];
            loginCell.TenderHomeAmount.text = [NSString stringWithFormat:@"%@",model.TenderHomeAmount];
        }
        
        loginCell.selectionStyle = UITableViewCellSelectionStyleNone;
        loginCell.backView.layer.shadowColor = [UIColor lightGrayColor].CGColor;
        loginCell.backView.layer.shadowOffset = CGSizeMake(0.5, 0.5);
        loginCell.backView.layer.shadowOpacity = YES;
        
       
        loginCell.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
    
        
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"LoginId"]) {
            [loginCell.login setTitle:@"立即投资" forState:UIControlStateNormal];
            loginCell.Clicked = ^(){
               self.tabBarController.selectedIndex = 1;

            };
        }else{ [loginCell.login setTitle:@"注册／登录" forState:UIControlStateNormal];
            //跳转登录注册页面
            loginCell.Clicked = ^(){
                NSLog(@"dianji");
                WelcomeLoginViewController *loginView = [[WelcomeLoginViewController alloc] init];
                loginView.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:loginView animated:NO];
            };
        
    }
        return loginCell;
    }else if(indexPath.row == self.homeArr.count+2){
        FooterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FOOTERTABLEVIEWCELL"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"FooterTableViewCell" owner:nil options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else {
        PurchaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PURCHASETABLECELL"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"PurchaseTableViewCell" owner:nil options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backView.layer.shadowColor = [UIColor lightGrayColor].CGColor;
         cell.backView.layer.shadowOffset = CGSizeMake(0.5, 0.5);
         cell.backView.layer.shadowOpacity = YES;
        
        if (self.homeArr.count) {
            
            BorrowGetHome *model = self.homeArr[indexPath.section];
            [cell setDataWithModel:model];
        }
        
        
        if (indexPath.row == 2) {
            
            if (Screen_Width == 320) {
                cell.projectName.font = [UIFont systemFontOfSize:13.0f];
                cell.UntiDetail.font = [UIFont systemFontOfSize:10.0f];
            }
        }else
        {
            if (Screen_Width == 320) {
                cell.projectName.font = [UIFont systemFontOfSize:13.0f];
                cell.UntiDetail.font = [UIFont systemFontOfSize:10.0f];
                
            }

        }
        return cell;
    }
    

 
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 20 + Screen_Width/4;
    }else if(indexPath.row == 1){
        return 100;
    }else if (indexPath.row == self.homeArr.count+2){
        return 90;
    }
    
    return 160;
    
}



//tableView的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    

    if (indexPath.row >1 && indexPath.row < self.homeArr.count + 2){
        
        CurrentViewController *currentView = [[CurrentViewController alloc] init];
        
        [UIView animateWithDuration:2 animations:^{
            if (self.homeArr.count) {
                BorrowGetHome *model = self.homeArr[indexPath.section];
                currentView.borrowId = model.BorrowId;
                currentView.item = [NSString stringWithFormat:@"%@%@",model.ProjectName ,model.Code];
                currentView.percentStr = [NSString stringWithFormat:@"%.2f",model.Proggress];

            }
            currentView.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:currentView animated:NO];
        }];
    }
    
}

/**
 *  时间对比
 *
 *  @param startDate 开始时间
 *  @param endDate 结束时间
 *
 *  @return 比较返回值
 */
- (NSString *)dateCompare:(NSString *)startDate and:(NSString *)endDate {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *startDay = [formatter dateFromString:startDate];
    NSDate *endDay = [formatter dateFromString:endDate];
    NSTimeInterval seconds = [endDay timeIntervalSinceDate:startDay];
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    
    [numberFormatter setPositiveFormat:@"0"];
    
    return [numberFormatter stringFromNumber:[NSNumber numberWithFloat:seconds / (60 * 60 * 24)]];
}


//轮播接口

- (void)getSearchImage{
    
    //http://open.wanyuanfu.net/api/user/openapi  Image.GetSearchImage
    
    NSDictionary *para = @{@"ClassImage":@"1"};
    [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Image.GetSearchImage" withParaments:para withSuccessBlock:^(NSDictionary *object) {
        
        for (NSDictionary *dict in object[@"Data"]) {
            NSString *imageStr = dict[@"PicsmallImage"];
            [self.imageArray addObject:imageStr];
        }
        [_mytableView reloadData];
    } withFailureBlock:^(NSError *error) {
        
    } progress:nil];
    
}

//头部轮播视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    
    if (_imageArray.count) {

        NSMutableArray *urlarr = [NSMutableArray array];
        for (NSString *str in _imageArray) {
            NSURL *imurl = [NSURL URLWithString:str];
            [urlarr addObject:imurl];
        }
        UIImage *placeholder = [UIImage imageNamed:@"SHOUYE_02"];
        ZLScrolling *zl = [[ZLScrolling alloc] initWithCurrentController:self frame:CGRectMake(0, 0, Screen_Width, 200) photos:urlarr placeholderImage:placeholder];
        _zl = zl;
        _zl.timeInterval = 1;
        _zl.pageControl.pageIndicatorTintColor = [UIColor redColor];
        _zl.delegate= self;
        _zl.view.frame = CGRectMake(0, 0, Screen_Width, 200 );
    }else{
        NSArray *arr = @[@"SHOUYE_02"];
        ZLScrolling *zl = [[ZLScrolling alloc] initWithCurrentController:self frame:CGRectMake(0, 0, Screen_Width, 200 ) photos:arr placeholderImage:nil];
        _zl = zl;
        _zl.timeInterval = 1;
        _zl.pageControl.pageIndicatorTintColor = [UIColor redColor];
        _zl.delegate= self;
        _zl.view.frame = CGRectMake(0, 0, Screen_Width, 200 );

    }
    
    return _zl.view;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 200 ;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

#pragma mark ---------------tableView结束---------------

-(void)clickBtn:(UIButton *)btn{
    
    NSLog(@"点击按钮");
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
     [self.mytableView.mj_header beginRefreshing];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, 20)];
    statusBarView.backgroundColor=[UIColor colorWithRed:0.76 green:0.12 blue:0.18 alpha:1];
    [self.view addSubview:statusBarView];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    [_mytableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];

}

//点击签到 调用[[UIApplication sharedApplication] keyWindow];
- (void)signIn{
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    _window = window;
    [UIView  animateWithDuration:0.2 animations:^{
        _backView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height)];
        _backView.backgroundColor = [UIColor colorWithRed:0.16 green:0.17 blue:0.21 alpha:0.5];
        [window addSubview:_backView];
        
    }];
    
    [_backView addTarget:self action:@selector(touchUp:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *sgnIn = [[UIView alloc] init];
    sgnIn.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"QDicon_03"]];
    sgnIn.layer.cornerRadius = 5;
    sgnIn.layer.masksToBounds = YES;
    sgnIn.userInteractionEnabled = YES;
    [_backView addSubview:sgnIn];

    [sgnIn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_backView);
        make.width.mas_equalTo(280);
        make.height.mas_equalTo(259);
    }];
    UILabel *lable1 = [[UILabel alloc] init];
    UILabel *lable2 = [[UILabel alloc] init];
    UILabel *lable3 = [[UILabel alloc] init];
    UIButton *button = [[UIButton alloc] init];
    UIButton *sureBtn = [[UIButton alloc] init];
    
    lable1.text = @"签到成功+5 积分";
    lable1.font = [UIFont systemFontOfSize:25.0f];
    lable1.textColor = [UIColor colorWithRed:0.92 green:0.25 blue:0.31 alpha:1.00];
    
    lable2.text = @"白金会员 DCanimal";
    lable2.textColor = [UIColor colorWithRed:0.92 green:0.25 blue:0.31 alpha:1.00];
    
    lable3.text = @"积分可以兑换现金和实物礼品";
    lable3.font = [UIFont systemFontOfSize:15.0f];
    lable3.textColor = [UIColor colorWithRed:0.92 green:0.25 blue:0.31 alpha:1.00];
    
    
    [button setTitle:@"如何赚取更多积分》" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:0.75 green:0.00 blue:0.01 alpha:1.00] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    
    [sureBtn setTitle:@"确认签到" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.titleLabel.font =[UIFont systemFontOfSize:15.0f];
    [sureBtn setBackgroundColor:[UIColor colorWithRed:0.93 green:0.37 blue:0.31 alpha:1.00]];
    sureBtn.layer.cornerRadius = 5;
    sureBtn.layer.masksToBounds = YES;
    
    [sureBtn addTarget:self action:@selector(touchUp:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [sgnIn addSubview:lable1];
    [sgnIn addSubview:lable2];
    [sgnIn addSubview:lable3];
    [sgnIn addSubview:button];
    [sgnIn addSubview:sureBtn];
    
    [lable1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(sgnIn.mas_centerX);
        make.topMargin.mas_equalTo(sgnIn.mas_top).offset(50);
    }];
    
    [lable2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(sgnIn.mas_centerX);
        make.topMargin.mas_equalTo(lable1.mas_bottom).offset(10);
    }];
    [lable3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(sgnIn.mas_centerX);
        make.topMargin.mas_equalTo(lable2.mas_bottom).offset(10);
    }];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(sgnIn.mas_centerX).offset(10);
        make.topMargin.mas_equalTo(lable3.mas_bottom).offset(20);
    }];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(sgnIn.mas_centerX);
        make.topMargin.mas_equalTo(button.mas_bottom).offset(10);
        make.width.mas_equalTo(lable3.mas_width);
        make.height.mas_equalTo(40);
    }];
   
}

//释放windows
- (void)touchUp:(UIButton *)tap{
    
    [self getDailyCheck];
    [_backView removeFromSuperview];
    
}

//获取定期
- (void)getHome{
    
//    http://test.open.wanyuanfu.net/api/user/openapi
    
    NSDictionary *para = @{};
    [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Borrow.GetHome" withParaments:para withSuccessBlock:^(NSDictionary *object) {
        [self.homeArr removeAllObjects];
        for (NSDictionary *dic in object[@"Data"]) {
           BorrowGetHome *homeModel = [BorrowGetHome mj_objectWithKeyValues:dic];
        
            [self.homeArr addObject:homeModel];

        }
        [_mytableView reloadData];
        
    } withFailureBlock:^(NSError *error) {
        
    } progress:nil];
}

//获取累计投资金额
-(void)getHomeAmount{
    
    NSDictionary *para = @{};
    [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Invest.GetHomeAmount" withParaments:para withSuccessBlock:^(NSDictionary *object) {
        
        NSDictionary *dict = [object[@"Data"] firstObject];
        BorrowGetHome *homeModel = [BorrowGetHome mj_objectWithKeyValues:dict];
        [_moneyArr addObject:homeModel];
    } withFailureBlock:^(NSError *error) {
        NSLog(@"%@",error);
    } progress:nil];
}



//MJ刷新
-(void)refresh
{
    
    //下拉刷新
    self.mytableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^
                                  {
                                      
                                      [self getHome];
                                      
                                      [self.mytableView.mj_header endRefreshing];
                                  }];
    
}


//每日签到
-(void)getDailyCheck{
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"LoginId"] isEqualToString:@""]) {
        WelcomeLoginViewController *loginView = [[WelcomeLoginViewController alloc] init];
        loginView.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginView animated:NO];
        
    }else{
        NSString *loginId = [[NSUserDefaults standardUserDefaults] objectForKey:@"LoginId"];
        NSDictionary *para = @{
                               @"LoginId":loginId
                               };
        
        [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Api.GetDailyCheck" withParaments:para withSuccessBlock:^(NSDictionary *object) {
            NSLog(@"%@",object);
            if ([object[@"Code"] isEqualToString:@"00000"]) {
                
                [ToastView showInfoWithStatus:[object[@"Data"] firstObject][@"Message"]];
            }else{
                [ToastView showInfoWithStatus:object[@"Message"]];
            }
            
        } withFailureBlock:^(NSError *error) {
            NSLog(@"%@",error);
        } progress:nil];

    }
    
  }

@end

